package com.timeriver.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import redis.clients.jedis.JedisPoolConfig;

/**
 * Redis配置类：使用 RedisTemplate
 */
@Configuration
public class RedisTemplateConfig {

    @Value("${spring.redis.host}")
    public String host;
    @Value("${spring.redis.password}")
    private String password;
    @Value("${spring.redis.port}")
    private int port;
    @Value("${spring.redis.jedis.pool.max-active}")
    private int maxActive;
    @Value("${spring.redis.jedis.pool.min-idle}")
    private int minIdle;
    @Value("${spring.redis.jedis.pool.max-idle}")
    private int maxIdle;

    private static volatile JedisConnectionFactory jedisConnectionFactory;

    /**
     * 单例模式创建Jedis连接工厂类对象
     * @return JedisConnectionFactory
     */
    private JedisConnectionFactory getInstance() {
        if (jedisConnectionFactory == null) {
            synchronized (JedisConnectionFactory.class) {
                if (jedisConnectionFactory == null) {
                    JedisPoolConfig poolConfig = new JedisPoolConfig();
                    poolConfig.setMaxTotal(maxActive);
                    poolConfig.setMaxIdle(maxIdle);
                    poolConfig.setMinIdle(minIdle);
                    JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(poolConfig);
                    RedisStandaloneConfiguration configuration = jedisConnectionFactory.getStandaloneConfiguration();
                    configuration.setHostName(host);
                    configuration.setPort(port);
                    configuration.setPassword(password);
                    this.jedisConnectionFactory = jedisConnectionFactory;
                }
            }
        }
        return jedisConnectionFactory;
    }

    @Bean(name = "redisTemplate")
    public RedisTemplate<Object, Object> initRedisTemplate() {
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(getInstance());
        return redisTemplate;
    }
}
